<template>
  <div class="logo-box-right">
    <el-col >
      <el-row :align="middle" justify="center"><input type="text" v-model="name" id="search-input">
        <el-button type="primary" class="btn-search" @click="search">搜索</el-button>
        <el-button type="primary" class="btn-add" @click="addProduct">添加商品</el-button>
        <el-button type="danger" @click="deleteSelected">删除选中</el-button>
        <el-button type="success" @click="batchOnOffShelf">一键上下架</el-button>
        <el-button type="info" @click="editSelected">修改选中</el-button>
        <el-button type="primary" plain @click="sortBySalesDesc">按销量降序</el-button>
        <el-button type="primary" plain @click="sortByStockAsc">按库存升序</el-button>
        <el-button type="success" @click="issueCoupons">一键发放优惠券</el-button>
        <el-button type="danger" @click="addActivity">发起活动</el-button></el-row>
      <el-row :align="middle" justify="center">
        <el-select v-model="selectedActivityId" placeholder="请选择活动" @change="onActivityChange" style="width: 200px;" @click="fetchActivities">
          <el-option v-for="act in activityList" :key="act.id" :label="act.name" :value="act.id" />
        </el-select>
        <el-select v-model="selectedCategoryId" placeholder="请选择分类" @change="onCategoryChange" style="width: 200px; margin-left: 10px;">
          <el-option v-for="category in categoryList" :key="category.id" :label="category.name" :value="category.id" />
        </el-select>
      </el-row>
    </el-col>


  </div>
  <!-- 模板修改：适配字段名和图片路径 -->
  <div class="book-list-box">
    <div class="book-list-box-wrapper">
      <div
          class="book-item"
          :class="{ 'off-shelf': product.is_on_shelf === 0 }"
          v-for="product in productList"
          :key="product.id"
          @click.stop
      >
        <!-- 新增：左上角复选框 -->
        <div class="checkbox-container">
          <input
              type="checkbox"
              :value="product.id"
              v-model="selectedProductIds"
              @click="toggleCheckbox(product.id)"
          />
        </div>

        <img :src="baseUrl + product.productImages[0]" alt="" width="150">
        <p>{{ product.name }}</p>
        <p class="gray-color">{{ product.description }}</p>
        <p>
          <span class="red-color">￥{{ product.price }}</span>
          <span class="gray-color">库存{{ product.stock }}</span>
          <span class="gray-color" style="margin-left: 10px;">商品ID:{{ product.id }}</span>
          <el-button v-if="selectedActivityId" type="primary" @click="openEditDiscountDialog" style="margin-left: 5px;">改折扣</el-button>        </p>
      </div>
    </div>
  </div><!-- 加载提示 -->
  <div v-if="loading" class="loading">正在加载...</div>
  <div v-if="finished" class="finished">没有更多了</div>
<!--  商品添加对话框-->
  <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      append-to-body
      @open="fetchCategories"
  >
    <div style="margin-bottom: 20px">
      <label style="display: block; margin-bottom: 8px; font-weight: 500;">商品名称</label>
      <el-input
          v-model="editData.name"
          placeholder="请输入商品名称"
      />
    </div><div style="margin-bottom: 20px">
      <label style="display: block; margin-bottom: 8px; font-weight: 500;">商品分类</label>
      <el-select v-model="editData.category_id" placeholder="请选择商品分类" style="width: 100%">
        <el-option
            v-for="category in categoryList"
            :key="category.id"
            :label="category.name"
            :value="category.id"
        />
      </el-select>
    </div><div style="margin-bottom: 20px">
      <label style="display: block; margin-bottom: 8px; font-weight: 500;">商品介绍</label>
      <el-input
          v-model="editData.description"
          placeholder="请输入"
      />
    </div>
    <div style="margin-bottom: 20px">
      <label style="display: block; margin-bottom: 8px; font-weight: 500;">商品售价</label>
      <el-input
          v-model="editData.price"
          placeholder="请输入商品售价"
      />
    </div><div style="margin-bottom: 20px">
      <label style="display: block; margin-bottom: 8px; font-weight: 500;">商品库存</label>
      <el-input
          v-model="editData.stock"
          placeholder="请输入商品库存"
      />
    </div>
    <div style="margin-bottom: 20px">
      <label style="display: block; margin-bottom: 8px; font-weight: 500;">商品图片</label>
      <div v-if="editData.productImages" style="margin-bottom: 10px">
        <img
            :src="baseUrl + editData.productImages"
            alt="预览"
            style="width: 80px; height: 80px; object-fit: cover; border-radius: 8px;"
          />
        </div>
      </div>
      <el-upload
        action="http://192.168.90.26:8080/uploade/uploading"
        list-type="picture-card"
        :auto-upload="true"
        :on-success="handleUploadSuccess"
        :limit="5"
        :on-exceed="handleExceed"
        style="display: inline-block;"
      >
        <el-button type="primary">上传图片</el-button>
        <template #tip>
          <div style="font-size: 12px; color: #888; margin-top: 8px">
            支持JPG/PNG格式，文件小于2MB，最多上传5张
          </div>
        </template>
      </el-upload>
    <div style="margin-bottom: 20px">
      <label style="display: block; margin-bottom: 8px; font-weight: 500;">商品状态</label>
      <el-radio-group v-model="editData.is_on_shelf">
        <el-radio :label="1">上架</el-radio>
        <el-radio :label="0">下架</el-radio>
      </el-radio-group>
    </div>
    <el-button type="primary" @click="dialogVisible = false">取消</el-button>
    <el-button type="primary" @click="saveProduct">确定</el-button>
  </el-dialog>
  <!-- 商品优惠券发放对话框 -->
  <el-dialog v-model="couponDialogVisible" title="发放商品优惠券" width="500px">
  <el-form>
    <el-form-item label="优惠券名称" label-width="100px">
      <el-input v-model="couponForm.name" placeholder="请输入优惠券名称"></el-input>
    </el-form-item>
    <el-form-item label="折扣" label-width="100px">
      <el-input-number v-model="couponForm.discount" :min="0.1" :max="1" :step="0.01" controls-position="right" placeholder="0.1-1"></el-input-number>
    </el-form-item>
    <el-form-item label="使用门槛" label-width="100px">
      <el-input v-model.number="couponForm.discount_condition" placeholder="满多少可用"></el-input>
    </el-form-item>
    <el-form-item label="开始时间" label-width="100px">
      <el-date-picker v-model="couponForm.start_time" type="datetime" placeholder="选择开始时间"></el-date-picker>
    </el-form-item>
    <el-form-item label="截止日期" label-width="100px">
      <el-date-picker v-model="couponForm.end_time" type="datetime" placeholder="选择截止日期"></el-date-picker>
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="couponDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitCoupons">确定发放</el-button>
  </template>
</el-dialog>

  <!-- 通用优惠券发布对话框 -->
  <el-dialog v-model="generalCouponDialogVisible" title="发布通用优惠券" width="500px">
    <el-form>
      <el-form-item label="名称" label-width="80px">
        <el-input v-model="generalCouponForm.name" placeholder="请输入优惠券名称"></el-input>
      </el-form-item>
      <el-form-item label="折扣" label-width="80px">
        <el-input-number v-model="generalCouponForm.discount" :min="0.1" :max="1" :step="0.01" controls-position="right" placeholder="0.1-1"></el-input-number>
      </el-form-item>
      <el-form-item label="使用门槛" label-width="80px">
        <el-input v-model.number="generalCouponForm.discount_condition" placeholder="满多少可用"></el-input>
      </el-form-item>
      <el-form-item label="开始时间" label-width="80px">
        <el-date-picker v-model="generalCouponForm.start_time" type="datetime" placeholder="选择开始时间"></el-date-picker>
      </el-form-item>
      <el-form-item label="截止日期" label-width="80px">
        <el-date-picker v-model="generalCouponForm.end_time" type="datetime" placeholder="选择截止日期"></el-date-picker>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="generalCouponDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitGeneralCoupon">发布优惠券</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="activityDialogVisible" title="发起活动" width="600px">
    <el-form>
      <el-form-item label="活动名称">
        <el-input v-model="activityForm.name" placeholder="请输入活动名称" />
      </el-form-item>
      <div v-for="product in selectedProducts" :key="product.id" style="margin-bottom: 10px;">
        <span>{{ product.name }}</span>
        <el-input-number
            v-model="activityForm.discounts[product.id]"
            :min="0.1"
            :max="1"
            :step="0.01"
            controls-position="right"
            placeholder="折扣(0.1~1)"
            style="width: 120px; margin-left: 10px;"
        />
      </div>
    </el-form>
    <template #footer>
      <el-button @click="activityDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitActivity">确定</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="editDiscountDialogVisible" title="修改商品折扣" width="600px">
    <div v-for="product in selectedProducts" :key="product.id" style="margin-bottom: 10px;">
      <span>{{ product.name }}</span>
      <el-input-number
          v-model="editDiscounts[product.id]"
          :min="0.1"
          :max="1"
          :step="0.01"
          controls-position="right"
          placeholder="折扣(0.1~1)"
          style="width: 120px; margin-left: 10px;"
      />
    </div>
    <template #footer>
      <el-button @click="editDiscountDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEditDiscount">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import axios from "axios";
import {useRouter} from "vue-router";
const router=useRouter()
const baseUrl=ref("http://192.168.90.26:8080/")
import {ref, onMounted, onUnmounted, computed} from 'vue'
import {ElMessage} from "element-plus";
const emit = defineEmits(['load-products'])
// 初始化数据
const dialogVisible = ref(false);
const dialogTitle = ref('添加商品');
let productList = ref([])  // 商品列表
const loading = ref(false)   // 是否正在加载
const finished = ref(false)  // 是否全部加载完成
const pageSize = ref(10)     // 每次加载数量
const name = ref("")
let selectedProductIds = ref([])
const editData = ref({
  id: null,
  name: '',
  description: '',
  productImages: [],
  category_id: null,
  price: 0,
  stock:0,
  is_on_shelf: 1,
});
const addProduct = () => {
  editData.value = {
    id: null,
    name: '',
    productImages: [],
    category_id: selectedCategoryId||null,
    price: 0,
    stock:0,
    is_on_shelf: 1,
  };
  dialogTitle.value = '添加商品';
  dialogVisible.value = true;
};
const activityDialogVisible = ref(false)
const activityForm = ref({
  name: '',
  discounts: {} // { 商品id: 折扣 }
})
const editDiscountDialogVisible = ref(false)
const editDiscounts = ref({})
const couponDialogVisible = ref(false)
let generalCouponDialogVisible = ref(false)
const couponForm = ref({
  name: '',                // 优惠券名称
  discount: 1,             // 折扣
  discount_condition: 0,   // 使用门槛
  start_time: '',          // 开始时间
  end_time: ''             // 截止日期
})
const generalCouponForm = ref({
  name: '',                // 优惠券名称
  discount: 1,
  discount_condition: 0,
  start_time: '',
  end_time: ''
})

const issueCoupons = () => {
  if (selectedProductIds.value.length > 0) {
    couponForm.value = {
      name: '',
      discount: 1,
      discount_condition: 0,
      start_time: '',
      end_time: ''
    }
    couponDialogVisible.value = true
  } else {
    generalCouponForm.value = {
      name: '',
      discount: 1,
      discount_condition: 0,
      start_time: '',
      end_time: ''
    }
    generalCouponDialogVisible.value = true
  }
}

const submitCoupons = () => {
  const payload = {
    name: couponForm.value.name,
    category_id: 2, // 商品优惠券
    product_ids: selectedProductIds.value,
    discount: couponForm.value.discount,
    discount_condition: couponForm.value.discount_condition,
    start_time: couponForm.value.start_time,
    end_time: couponForm.value.end_time
  }
  axios.post('/coupon/add', payload).then(res => {
    ElMessage.success('优惠券发放成功')
    couponDialogVisible.value = false
  }).catch(error => {
    console.error(error)
    ElMessage.error('优惠券发放失败')
  })
}

const submitGeneralCoupon = () => {
  const payload = {
    name: generalCouponForm.value.name,
    category_id: 1, // 通用优惠券
    discount: generalCouponForm.value.discount,
    discount_condition: generalCouponForm.value.discount_condition,
    start_time: generalCouponForm.value.start_time,
    end_time: generalCouponForm.value.end_time
  }
  axios.post('/coupon/add', payload).then(res => {
    ElMessage.success('通用优惠券发布成功')
    generalCouponDialogVisible.value = false
  }).catch(error => {
    console.error(error)
    ElMessage.error('通用优惠券发布失败')
  })
}
function openEditDiscountDialog() {
  // 初始化折扣
  editDiscounts.value = {}
  selectedProducts.value.forEach(p => {
    // 查找当前活动商品的折扣
    const found = activityProducts.value.find(ap => ap.id === p.id)
    editDiscounts.value[p.id] = found ? found.discount : 1
  })
  editDiscountDialogVisible.value = true
}

function submitEditDiscount() {
  // 提交格式：{ activityId, products: [{id, discount}] }
  const payload = Object.entries(editDiscounts.value).map(([id, discount]) => ({
    activity_id: selectedActivityId.value, // 活动 ID（确保 selectedActivityId.value 存在）
    product_id: Number(id), // 产品 ID（将字符串键转为数字）
    discount // 折扣值（保持原类型）
  }));
  axios.post('/activity_product/update', payload).then(res => {
    editDiscountDialogVisible.value = false
    // 刷新活动商品
    onActivityChange()
  })
}
const selectedProducts = computed(() =>
    productList.value.filter(p => selectedProductIds.value.includes(p.id))
)
const activityList = ref([]) // 活动列表
const selectedCategoryId = ref(null) // 选中的分类ID
const selectedActivityId = ref(null)
const activityProducts = ref([]) // 当前活动商品及折扣

function fetchCategories() {
  axios.get('category/findAll').then(res => {
    categoryList.value = res.data;
  });
}

function fetchActivities() {
  axios.get('/activity/list').then(res => {
    activityList.value = res.data
  })
}

function onCategoryChange() {
  currentPage.value = 1;
  finished.value = false;
  search();
}

function onActivityChange() {
  axios.get('/activity/list', { params: { id: selectedActivityId.value } }).then(res => {

    activityProducts.value =res.data[0].activityProducts
    // 自动勾选
    selectedProductIds.value = activityProducts.value.map(p => p.product_id)
  })
}
function addActivity() {
  if (selectedProductIds.value.length === 0) {
    ElMessage.warning('请至少选择一个商品');
    return;
  }
  activityForm.value = { name: '', discounts: {} }
  selectedProducts.value.forEach(p => {
    activityForm.value.discounts[p.id] = 1 // 默认1折
  })
  activityDialogVisible.value = true
}

function submitActivity() {
  if (!activityForm.value.name) {
    ElMessage.warning('活动名称不能为空');
    return;
  }
  // 提交格式：{ name, products: [{id, discount}] }
  const payload = {
    name: activityForm.value.name,
    activityProducts: Object.entries(activityForm.value.discounts).map(([id, discount]) => ({
      product_id: Number(id),
      discount
    }))
  }
  axios.post('/activity/add', payload).then(res => {
    // 处理结果
    activityDialogVisible.value = false
    // 刷新活动/商品列表
  })
}
function sortByStockAsc() {
  // 复制一份数组，避免直接修改响应式引用
  productList.value = [...productList.value].sort((a, b) => {
    // 先判断库存是否为数字
    const stockA = Number(a.stock) || 0;
    const stockB = Number(b.stock) || 0;
    return stockA - stockB;
  });
}
let categoryList= ref([])
const search = () => {
    currentPage.value = 1
    finished.value = false
    loadProducts()
  loading.value = true
  axios.get("product/list", {
    params: {
  name: name.value,
  category_id: selectedCategoryId.value || undefined,
  page: currentPage.value,
  page_size: pageSize.value
}
  }).then(res => {
    // 获取新数据
    productList = res.data
    if (productList.length < pageSize.value) {
      finished.value = true
    }
    loading.value = false
  }).catch(error => {
    console.error(error)
    loading.value = false
  })
}
// 加载商品函数
const currentPage = ref(1) // 当前页码

// 加载商品函数
const loadProducts = () => {
  if (loading.value || finished.value) return; // 防止重复请求
  loading.value = true;
  axios.get("product/list", {
    params: {
  name: name.value,
  page: currentPage.value,
  page_size: pageSize.value
}
  }).then(res => {
    const newProducts = res.data;
    if (currentPage.value === 1) {
      productList.value = [...newProducts];
    } else {
      productList.value = [...productList.value, ...newProducts];
    }
    if (newProducts.length < pageSize.value) {
      finished.value = true;
    } else {
      currentPage.value += 1; // 只在这里递增
    }
    loading.value = false;
  }).catch(error => {
    console.error(error);
    loading.value = false;
  });
};


// 滚动事件处理函数
const handleScroll = () => {
  const scrollBottom = window.innerHeight + window.scrollY;
  const threshold = document.body.offsetHeight - 50;
  if (scrollBottom >= threshold && !loading.value && !finished.value) {
    loadProducts(); // 不要传currentPage+1
  }
};


// 在mounted时绑定滚动事件，并且初始化加载第一页
onMounted(() => {
  loadProducts()
  fetchCategories()
  window.addEventListener('scroll', handleScroll)
})

// 在卸载时移除事件
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
function handleExceed() {
  alert('最多只能上传5张图片');
  return false;
}
function handleUploadSuccess(res) {
  editData.value.productImages.push(res)
}
const saveProduct = () => {
  let url = editData.value.id ? "product/update" : "product/add";
  axios.post(url, editData.value).then(res => {
    if (res.data) {
      ElMessage.success(editData.value.id ? '修改成功' : '添加成功');
      dialogVisible.value = false;
      // 自动写日志
      axios.post('/log/add', {
        product_id: editData.value.id || res.data.id,
        change_quantity: editData.value.stock,
        change_reason: editData.value.id ? '修改商品' : '添加商品',
        change_time: new Date()
      })
      // 刷新商品列表
      currentPage.value = 1;
      finished.value = false;
      search(currentPage.value);
    } else {
      ElMessage.error(editData.value.id ? '修改失败' : '添加失败');
    }
  });
}
const toggleCheckbox=(id)=>{
  if (selectedProductIds.value.includes(id)) {
    selectedProductIds.value = selectedProductIds.value.filter(item => item !== id);
  } else {
    selectedProductIds.value.push(id);
  }
}
const deleteSelected = () => {
  if (selectedProductIds.value.length === 0) {
    ElMessage.warning('请至少选择一个商品');
    return;
  }
  axios.post("http://192.168.90.26:8080/product/delete", selectedProductIds.value, {
    headers: {
      'Content-Type': 'application/json'
    }
  })    .then(res => {
      if (res.data) {
        ElMessage.success('删除成功');
        // 刷新商品列表
        currentPage.value = 1;
        finished.value = false;
        loadProducts(currentPage.value);
      } else {
        ElMessage.error('删除失败');
      }
    })
    .catch(error => {
      console.error(error);
      ElMessage.error('请求失败');
    });
};
function batchOnOffShelf(){
  axios.post("product/batchOnOffShelf", selectedProductIds.value ,{
    headers: {
      'Content-Type': 'application/json'
    }
  })
    .then(res => {
      if (res.data) {
        ElMessage.success('上下架成功');
        // 刷新商品列表
        currentPage.value = 1;
        finished.value = false;
        loadProducts(currentPage.value);
      } else {
        ElMessage.error('失败');
      }
    })
    .catch(error => {
      console.error(error);
    })
}
function editSelected(){
  if (selectedProductIds.value.length === 0){
    ElMessage.warning('请至少选择一个商品');
  }else if (selectedProductIds.value.length > 1){
    ElMessage.warning('只能选择一个商品');
  }else{
    for (let i in productList.value) {
      if (productList.value[i].id === selectedProductIds.value[0]){
        editData.value = productList.value[i];
        dialogTitle.value = '修改商品';
        dialogVisible.value = true;
      }
    }
  }
}

const sendCoupon = (user) => {
  currentUser.value = user
  couponForm.value = {
    name: '',
    discount: 1,
    discount_condition: 0,
    start_time: '',
    end_time: ''
  }
  couponDialogVisible.value = true
}

</script>

<style scoped>
.logo-box-right{
  width: 100%;
  height: 120px;
  display: flex;
  align-items: center;
}
.btn-search{
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
.btn-search:hover{
  background-color: #ff006e;
}

#search-input{
  width: 200px;
  height: 40px;
  outline: none;
  box-sizing: border-box;
  border: 1px solid #808080;
}
.book-list-box {
  position: relative;
  min-height: 400px;
}
.book-list-box-wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.book-item {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.book-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.12);
}

.book-item img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-bottom: 1px solid #eee;
}

.book-item p {
  padding: 8px 15px;
}

.gray-color {
  color: #7f8c8d;
  font-size: 14px;
}

.red-color {
  color: #e74c3c;
  font-weight: bold;
  font-size: 17px;
  margin-right: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}


.filter-section select {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 15px;
  background-color: #f9f9f9;
  width: 200px;
}


@media (max-width: 768px) {
  .book-list-box-wrapper {
    grid-template-columns: repeat(2, 1fr);
  }

  .filter-section select {
    width: 48%;
    margin-right: 0;
  }
}

@media (max-width: 480px) {
  .book-list-box-wrapper {
    grid-template-columns: 1fr;
  }

  .filter-section select {
    width: 100%;
  }
}
.off-shelf {
  position: relative;
  filter: grayscale(0.7) brightness(0.9);
  opacity: 0.7;
}

.off-shelf::after {
  content: "已下架";
  position: absolute;
  top: 12px;
  right: -18px;
  background: #e74c3c;
  color: #fff;
  font-size: 14px;
  font-weight: bold;
  padding: 2px 12px;
  border-radius: 12px;
  transform: rotate(18deg);
  box-shadow: 0 2px 8px rgba(231,76,60,0.15);
  z-index: 2;
  letter-spacing: 2px;
  pointer-events: none;
}
.checkbox-container input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}
</style>